package jsyf.oa.service.yuce;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.yuce.YuceMainDao;
import jsyf.oa.dao.yuce.YuceSubDao;
import jsyf.oa.entity.system.AuditEntity;
import jsyf.oa.entity.system.AuditHistoryEntity;
import jsyf.oa.entity.system.UserEntity;
import jsyf.oa.entity.yuce.YuceMainEntity;
import jsyf.oa.entity.yuce.YuceSubEntity;
import jsyf.oa.facade.yuce.YuceMainFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@SuppressWarnings("all")
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class YuceMainService implements YuceMainFacade {

    @Autowired
    private YuceMainDao yuceMainDao;
    @Autowired
    private YuceSubDao yuceSubDao;
    @Autowired
    private AuditHistoryDao auditHistoryDao;
    @Autowired
    private AuditDao auditDao;
    @Autowired
    private CopierDao copierDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CompanyDao companyDao;

    @Override
    public JSONObject select(String jsonData) {
        String type = "";
        JSONObject jsonObject = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonObject.getString("userId");
        String companyId = jsonObject.getString("companyId");
        String date = jsonObject.getString("date");
        String companyIds = "";
        String ids = companyDao.getChilderCompanyByCompanyId(companyId).getString("companyIds");
        //如果有下级
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(ids)) {
            //如果有多个下级
            if (ids.indexOf(",") >= 0) {
                String[] idsSplit = ids.split(",");
                for (String id : idsSplit) {
                    companyIds += "'" + id + "',";
                }
            } else {
                //如果只有一个下级
                companyIds += "'" + ids + "',";
            }
        }
        //把自己公司的Id加入
        companyIds += "'" + companyId + "',";
        companyIds = companyIds.substring(0, companyIds.length() - 1);
        if (jsonObject.containsKey("type")) {
            type = "1";
        }
        try {
            date = getFriday(date);
        } catch (Exception e) {
        }
        String regionId = null;
        if (jsonObject.containsKey("regionId")) {
            regionId = jsonObject.getString("regionId");
        }
        String firstMonth = date.substring(0, 7);
        String secondMonth = DateUtils.getAfterMonth(firstMonth);
        String thirdMonth = DateUtils.getAfterMonth(secondMonth);
        JSONObject result = new JSONObject();
        //如果不传区域，这是点击公司，查看整个公司的数据，只从表里拿
        if (StringUtils.isBlank(regionId)) {
            List<JSONObject> yuceMainList = yuceMainDao.getJSONListByCondition(" AND DAY=? and status=1 and COMPANY_ID in (" + companyIds + ")", new Object[]{date});
            String mainIds = "";
            if (null != yuceMainList && yuceMainList.size() > 0) {
                for (int i = 0; i < yuceMainList.size(); i++) {
                    mainIds += "'" + yuceMainList.get(i).getString("id") + "',";
                }
                mainIds = mainIds.substring(1, mainIds.length() - 2);
            }
            YuceMainEntity yuceMainEntity = new YuceMainEntity();
            yuceMainEntity.setStatus(-2);
            yuceMainEntity.setThirdMonth(thirdMonth);
            yuceMainEntity.setSecondMonth(secondMonth);
            yuceMainEntity.setFirstMonth(firstMonth);
            yuceMainEntity.setDay(date);
            try {
                //查询公司的上周数据
                JSONObject json = selectBeforeWeekByCompanyId(yuceMainEntity.getId(), date, companyIds);
                yuceMainEntity.setFirstMonthBef(new BigDecimal(json.getString("firstMonth")));
                yuceMainEntity.setSecondMonthBef(new BigDecimal(json.getString("secondMonth")));
                yuceMainEntity.setThirdMonthBef(new BigDecimal(json.getString("thirdMonth")));
                //查询公司的本周数据
                JSONObject jsonSum = selectNumberByCompanyId(date, companyIds);
                yuceMainEntity.setActualSaleRemark(new BigDecimal(jsonSum.getString("number")));
                //yuceMainEntity.setFirstMonthBef(new BigDecimal(jsonSum.getString("firstMonthBef")));
                yuceMainEntity.setFirstMonthSub(new BigDecimal(jsonSum.getString("firstMonthSub")));
                yuceMainEntity.setFirstMonthYuce(new BigDecimal(jsonSum.getString("firstMonthYuce")));
                //yuceMainEntity.setSecondMonthBef(new BigDecimal(jsonSum.getString("secondMonthBef")));
                yuceMainEntity.setSecondMonthSub(new BigDecimal(jsonSum.getString("secondMonthSub")));
                yuceMainEntity.setSecondMonthYuce(new BigDecimal(jsonSum.getString("secondMonthYuce")));
                //yuceMainEntity.setThirdMonthBef(new BigDecimal(jsonSum.getString("thirdMonthBef")));
                yuceMainEntity.setThirdMonthSub(new BigDecimal(jsonSum.getString("thirdMonthSub")));
                yuceMainEntity.setThirdMonthYuce(new BigDecimal(jsonSum.getString("thirdMonthYuce")));
            } catch (Exception e) {
            }
            yuceMainEntity.setCompanyId(companyId);
            result.put("sub", yuceSubDao.getSubListByMainId(mainIds, firstMonth, secondMonth, thirdMonth, false));
            result.put("main", (JSONObject) JSON.toJSON(yuceMainEntity));
        } else {
            //如果传了区域，这是点击区域，每当周五第一次点击的时候，关联查询数据，保存之后是查存库的数据
            List<JSONObject> yuceMainList = yuceMainDao.getJSONListByCondition(" AND DAY=? and BIG_REGION_ID=?", new Object[]{date, regionId});
            //判断主表是否有数据，有的话就是保存后读存库的数据
            if (null != yuceMainList && yuceMainList.size() > 0) {
                date = date.substring(0, 7);
                YuceMainEntity yuceMainEntity = JSON.toJavaObject(yuceMainList.get(0), YuceMainEntity.class);
                result.put("sub", yuceSubDao.getSubListByMainId(yuceMainEntity.getId(), yuceMainEntity.getFirstMonth(), yuceMainEntity.getSecondMonth(), yuceMainEntity.getThirdMonth(), false));
                yuceMainEntity.setFirstMonth(firstMonth);
                yuceMainEntity.setSecondMonth(secondMonth);
                yuceMainEntity.setThirdMonth(thirdMonth);
                try {
                    JSONObject json = selectBeforeWeekByRegionId(yuceMainEntity.getId(), date, regionId);
                    yuceMainEntity.setFirstMonthBef(new BigDecimal(json.getString("firstMonth")));
                    yuceMainEntity.setSecondMonthBef(new BigDecimal(json.getString("secondMonth")));
                    yuceMainEntity.setThirdMonthBef(new BigDecimal(json.getString("thirdMonth")));
                } catch (Exception e) {
                }
                result.put("main", yuceMainEntity);
                result.put("auditors", auditDao.getIBaseEntityByCondition(" AND MAIN_ID=? order By auditSort", new Object[]{yuceMainEntity.getId()}));
                result.put("history", auditHistoryDao.getEntityListByCondition(" AND MAIN_ID=? AND AUDIT_FLAG='2'", new Object[]{yuceMainEntity.getId()}));
            } else {
                //主表没数据，则是关联查询，查询实时的数据
                result.put("sub", selectFirstForFriday(userId, companyId, regionId, date, type));
                YuceMainEntity yuceMainEntity = new YuceMainEntity();
                yuceMainEntity.setStatus(-1);
                yuceMainEntity.setThirdMonth(thirdMonth);
                yuceMainEntity.setSecondMonth(secondMonth);
                yuceMainEntity.setFirstMonth(firstMonth);
                yuceMainEntity.setDay(date);
                yuceMainEntity.setCompanyId(companyId);
                yuceMainEntity.setBigRegionId(regionId);
                try {
                    JSONObject json = selectBeforeWeekByRegionId(yuceMainEntity.getId(), date, regionId);
                    yuceMainEntity.setFirstMonthBef(new BigDecimal(json.getString("firstMonth")));
                    yuceMainEntity.setSecondMonthBef(new BigDecimal(json.getString("secondMonth")));
                    yuceMainEntity.setThirdMonthBef(new BigDecimal(json.getString("thirdMonth")));
                } catch (Exception e) {
                }
                result.put("main", (JSONObject) JSON.toJSON(yuceMainEntity));
                JSONObject auditAndcoiper = getJSONByAuditAndCopier(userId, null, "");
                result.put("auditors", FastJsonConvert.convertJSONToArray(auditAndcoiper.getString("auditors"), JSONObject.class));
            }
        }
        return result;
    }

    //每周五第一次加载时获取新的数据
    private List<JSONObject> selectFirstForFriday(String userId, String companyId, String regionId, String
            date, String type) {
        String firstMonth = date.substring(0, 7);
        String secondMonth = DateUtils.getAfterMonth(firstMonth);
        String thirdMonth = DateUtils.getAfterMonth(secondMonth);
        int nowDay = -1;
        try {
            nowDay = DateUtils.dayForWeek(date);
        } catch (Exception e) {
        }
        if (5 == nowDay) {
            return yuceSubDao.getFirstByUserIdAndCompanyId(userId, companyId, regionId, getSQLMonth(firstMonth), getSQLMonth(secondMonth), getSQLMonth(thirdMonth), type);
        } else {
            return null;
        }
    }

    @Override
    public Boolean save(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        YuceMainEntity yuceMainEntity = JSON.parseObject(json.getString("main"), YuceMainEntity.class);
        //插入的是周五的日期
        try {
            yuceMainEntity.setDay(getFriday(yuceMainEntity.getDay()));
        } catch (Exception e) {
            yuceMainEntity.setDay(yuceMainEntity.getDay());
        }
        //如果有ID 则为修改，不然就是添加
        String mainId = yuceMainEntity.getId();
        if (StringUtils.isBlank(mainId)) {
            yuceMainDao.add(yuceMainEntity);
            mainId = yuceMainEntity.getId();
        } else {
            //更新主表信息
            yuceMainEntity.setCreateTime(((YuceMainEntity) yuceMainDao.getIBaseEntityById(mainId)).getCreateTime());
            yuceMainDao.update(yuceMainEntity);
            //删除现有的审核人和抄送人
            auditDao.removeByCondition("AND MAIN_ID = ? AND MODULE_NAME='yuceMainType' ", new String[]{mainId});
            //copierDao.removeByCondition("AND MAIN_ID = ? AND MODULE_NAME='yuceMainType' ", new String[]{mainId});
        }
        //删除子表全部，重新添加
        yuceSubDao.removeByCondition(" AND MAIN_ID=?", new String[]{mainId});
        //添加子表信息
        List<JSONObject> jsonObjectList = FastJsonConvert.convertJSONToArray(json.getString("sub"), JSONObject.class);
        if (null != jsonObjectList && jsonObjectList.size() > 0) {
            for (JSONObject jsonObject : jsonObjectList) {
                YuceSubEntity yuceSubEntity = new YuceSubEntity();
                yuceSubEntity.setMainId(mainId);
                yuceSubEntity.setModelName(jsonObject.getString("modelName"));
                yuceSubEntity.setMonth(yuceMainEntity.getFirstMonth());
                yuceSubEntity.setNumber(new BigDecimal(jsonObject.getString("firstMonth")));
                yuceSubDao.add(yuceSubEntity);
                yuceSubEntity.setMonth(yuceMainEntity.getSecondMonth());
                yuceSubEntity.setNumber(new BigDecimal(jsonObject.getString("secondMonth")));
                yuceSubDao.add(yuceSubEntity);
                yuceSubEntity.setMonth(yuceMainEntity.getThirdMonth());
                yuceSubEntity.setNumber(new BigDecimal(jsonObject.getString("thirdMonth")));
                yuceSubDao.add(yuceSubEntity);
            }
        }
        JSONObject auditAndcoiper = getJSONByAuditAndCopier(yuceMainEntity.getCreateUserId(), mainId, yuceMainEntity.getAuditorId());
        //获取审核人
        List<AuditEntity> auditList = (List<AuditEntity>) (Object) auditDao.getIBaseEntityByCondition("and main_id=? and module_name=? order by audit_sort", new Object[]{mainId, "yuceMainType"});
        if (auditList.size() > 0 && !yuceMainEntity.getStatus().equals("-1")) {
            AuditEntity auditEntity = auditList.get(0);
            yuceMainEntity.setAuditorName(auditEntity.getAuditorName());
            yuceMainEntity.setAuditorId(auditEntity.getAuditorId());
            yuceMainDao.update(yuceMainEntity);
        }
        return true;
    }

    //将传来日期，得到对应的周五
    private String getFriday(String date) throws Exception {
        int nowDay = DateUtils.dayForWeek(date);
        if (5 == nowDay) {
            return date;
        } else {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.setTime(format.parse(date));
            c.add(Calendar.DATE, 5 - nowDay);
            return format.format(c.getTime());
        }
    }

    //获取区域的上一周预测
    private JSONObject selectBeforeWeekByRegionId(String mainId, String date, String regionId) throws Exception {
        JSONObject json = new JSONObject();
        //传来时间-7获取上周五的时间
        date = getFriday(date);
        date = getAddDay(date, -7);
        //查询上周五的主表信息
        List<JSONObject> yuceMainList = yuceMainDao.getJSONListByCondition(" AND day=? AND BIG_REGION_ID=? ", new Object[]{date, regionId});
        if (null != yuceMainList && yuceMainList.size() > 0) {
            //得到上周对应的主表实体信息
            YuceMainEntity yuceMainEntity = JSON.toJavaObject(yuceMainList.get(0), YuceMainEntity.class);
            //上周的预测就是本周的上周预测值
            if (null != yuceMainEntity) {
                json.put("firstMonth", yuceMainEntity.getFirstMonthYuce());
                json.put("secondMonth", yuceMainEntity.getSecondMonthYuce());
                json.put("thirdMonth", yuceMainEntity.getThirdMonthYuce());
                return json;
            }
        }
        json.put("firstMonth", "0.00");
        json.put("secondMonth", "0.00");
        json.put("thirdMonth", "0.00");
        return json;
    }

    //获取公司的上一周预测
    private JSONObject selectBeforeWeekByCompanyId(String mainId, String date, String companyIds) throws Exception {
        JSONObject json = new JSONObject();
        //传来时间-7获取上周五的时间
        date = getFriday(date);
        date = getAddDay(date, -7);
        //查询上周五的主表信息
        List<JSONObject> yuceMainList = yuceMainDao.getJSONListByCondition(" AND day=? and status=1 AND COMPANY_ID in (" + companyIds + ") ", new Object[]{date});
        if (null != yuceMainList && yuceMainList.size() > 0) {
            BigDecimal firstMonth = new BigDecimal("0.00");
            BigDecimal secondMonth = new BigDecimal("0.00");
            BigDecimal thirdMonth = new BigDecimal("0.00");
            //得到上周对应的主表实体信息
            for (int i = 0; i < yuceMainList.size(); i++) {
                YuceMainEntity yuceMainEntity = JSON.toJavaObject(yuceMainList.get(i), YuceMainEntity.class);
                firstMonth = firstMonth.add(yuceMainEntity.getFirstMonthYuce());
                secondMonth = firstMonth.add(yuceMainEntity.getSecondMonthYuce());
                thirdMonth = firstMonth.add(yuceMainEntity.getThirdMonthYuce());
            }
            //上周的预测就是本周的上周预测值
            json.put("firstMonth", firstMonth);
            json.put("secondMonth", secondMonth);
            json.put("thirdMonth", thirdMonth);
            return json;

        }
        json.put("firstMonth", "0.00");
        json.put("secondMonth", "0.00");
        json.put("thirdMonth", "0.00");
        return json;
    }

    //获取本周公司的合计
    private JSONObject selectNumberByCompanyId(String date, String companyIds) throws Exception {
        JSONObject json = new JSONObject();
        //查询上周五的主表信息
        List<JSONObject> yuceMainList = yuceMainDao.getJSONListByCondition(" AND day=? and status=1 AND COMPANY_ID in (" + companyIds + ")", new Object[]{date});
        if (null != yuceMainList && yuceMainList.size() > 0) {
            String mainIds = "";
            for (int i = 0; i < yuceMainList.size(); i++) {
                mainIds += "'" + yuceMainList.get(i).getString("id") + "',";
            }
            mainIds = mainIds.substring(1, mainIds.length() - 2);
            //根据新的信息查子表
            JSONObject yuceMainNumberSum = yuceMainDao.getBeforeWeekYuceSum(mainIds);
            if (null != yuceMainNumberSum) {
                return yuceMainNumberSum;
            }
        }
        json.put("firstMonthBef", "0.00");
        json.put("secondMonthBef", "0.00");
        json.put("thirdMonthBef", "0.00");
        json.put("firstMonthSub", "0.00");
        json.put("secondMonthSub", "0.00");
        json.put("thirdMonthSub", "0.00");
        json.put("firstMonthYuce", "0.00");
        json.put("secondMonthYuce", "0.00");
        json.put("thirdMonthYuce", "0.00");
        return json;
    }

    //获取几天后的日期
    private String getAddDay(String date, Integer day) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(date));
        c.add(Calendar.DATE, day);
        return format.format(c.getTime());
    }

    //获取SQL拼装时候的日期类型
    private String getSQLMonth(String date) {
        if (date.substring(5, 7).startsWith("0")) {
            date = date.substring(6);
        } else {
            date = date.substring(5, 7);
        }
        return date + "月";
    }

    @Override
    public List<JSONObject> getModels(String companyId, String date, String regionId, String userId) {
        List<JSONObject> models = new ArrayList<JSONObject>();
        try {
            date = getFriday(date);
        } catch (Exception e) {
        }
        JSONObject result = new JSONObject();
        List<JSONObject> yuceMainList = yuceMainDao.getJSONListByCondition(" AND DAY=? and BIG_REGION_ID=?", new Object[]{date, regionId});
        if (null != yuceMainList && yuceMainList.size() > 0) {
            date = date.substring(0, 7);
            YuceMainEntity yuceMainEntity = JSON.toJavaObject(yuceMainList.get(0), YuceMainEntity.class);
            models = yuceSubDao.getSubListByMainId(yuceMainEntity.getId(), yuceMainEntity.getFirstMonth(), yuceMainEntity.getSecondMonth(), yuceMainEntity.getThirdMonth(), false);
        } else {
            models = selectFirstForFriday(userId, companyId, regionId, date, "1");

        }

        return models;
    }

    //获取抄送人和收件人
    public JSONObject getJSONByAuditAndCopier(String userId, String mainId, String auditFlag) {
        JSONObject results = new JSONObject();
        String userIds = checkDao.getParentByUserId(userId,true);//能看到他的上级人员
        //获取审核人
        List<JSONObject> auditors = new ArrayList<>();
        //第一审核人为销售管理经理
        List<JSONObject> jsonObject = userDao.getUserByUserIdAndRoleName(userIds, "销售管理", userId);
        if (jsonObject.size() > 0) {
            auditors.add(jsonObject.get(0));
        }
        if (mainId != null && auditors.size() > 0) {
            //mainId不为空才添加到数据库，否则只是获取
            for (int i = 0; i < auditors.size(); i++) {
                AuditEntity auditEntity = new AuditEntity();
                auditEntity.setAuditorId(auditors.get(i).getString("userId"));
                auditEntity.setAuditorName(auditors.get(i).getString("auditorName"));
                auditEntity.setRoleName(auditors.get(i).getString("roleName"));
                auditEntity.setAuditSort(i);
                if (i == 0 && !auditFlag.equals("-1")) {
                    //设置第一审核人状态
                    auditEntity.setAuditFlag(0);
                } else {
                    auditEntity.setAuditFlag(-1);
                }
                auditEntity.setModuleName("yuceMainType");//合同类型
                auditEntity.setMainId(mainId);
                auditDao.add(auditEntity);
            }
        }
        results.put("auditors", auditors);
/*//查询抄送人
        List<JSONObject> copiers = new ArrayList<>();
        StringBuffer exUserIds = new StringBuffer();
        for (int i = 0; i < auditors.size(); i++) {
            exUserIds.append(" '" + auditors.get(i).getString("userId") + "' ,");
        }
        String condition = "";
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(exUserIds.toString())) {
            condition = "and v_sys_part_time_for_report.`userId` not in (" + exUserIds.substring(0, exUserIds.length() - 1) + ")";
        }
        copiers = userDao.getUserByUserIdAndRoleName(userIds, "", userId, condition);
        if (mainId != null && copiers.size() > 0) {
            //mainId不为空才添加到数据库，否则只是获取
            for (int i = 0; i < copiers.size(); i++) {
                CopierEntity copierEntity = new CopierEntity();
                copierEntity.setCopierId(copiers.get(i).getString("userId"));
                copierEntity.setCopierName(copiers.get(i).getString("copierName"));
                copierEntity.setModuleName("yuceMainType");//合同类型
                copierEntity.setMainId(mainId);
                copierDao.add(copierEntity);
            }
        }
        results.put("copiers", copiers);*/
        return results;
    }

    @Override
    public Boolean applyAudit(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = jsonPalams.getString("id");//获取主表Id
        String auditFlag = jsonPalams.getString("auditFlag");//审核状态
        String userId = jsonPalams.getString("userId");//当前审核人ID
        String advise = jsonPalams.getString("advise");//意见
        UserEntity userEntity = userDao.getById(userId);//获取当前审核人信息
        YuceMainEntity yuceMainEntity = (YuceMainEntity) yuceMainDao.getIBaseEntityById(mainId);//合同主表信息
        //添加历史审核记录
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setMainId(mainId);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditorId(userId);
        auditHistoryEntity.setAuditorName(userEntity.getName());
        auditHistoryEntity.setAuditTime(auditHistoryDao.getCurrentTime());
        auditHistoryEntity.setAuditType(6);//预测是6
        auditHistoryDao.add(auditHistoryEntity);
        //更新当前审核人的--审核表记录
        List<AuditEntity> auditEntityList = (List<AuditEntity>) (Object) auditDao.getIBaseEntityByCondition("and main_id=? and module_name=? and AUDITOR_ID=?", new Object[]{mainId, "yuceMainType", userId});
        if (null != auditEntityList && auditEntityList.size() > 0) {
            AuditEntity auditEntity = auditEntityList.get(0);
            auditEntity.setAuditFlag(Integer.parseInt(auditFlag));
            auditEntity.setAuditAdvise(advise);
            auditEntity.setAuditTime(auditDao.getCurrentTime());
            auditDao.update(auditEntity);
        }
        //修改主表审核信息----->>>-1未到轮次/初始状态>>>0当前等待审核>>>1通过>>>2驳回
        List<AuditEntity> auditList = (List<AuditEntity>) (Object) auditDao.getIBaseEntityByCondition("and main_id=? and module_name=? order by audit_sort", new Object[]{mainId, "yuceMainType"});
        for (int i = 0; i < auditList.size(); i++) {
            AuditEntity audit = auditList.get(i);
            if (audit.getAuditorId().equals(userId)) {
                //如果是驳回，修改主表状态为驳回->2
                if (auditFlag.equals("2")) {
                    yuceMainEntity.setStatus(2);
                    yuceMainDao.update(yuceMainEntity);
                    break;
                }
                //如果是最后一个人审核通过，标记主表状态为通过->1
                if (auditList.size() - 1 == i) {
                    yuceMainEntity.setStatus(1);
                    yuceMainDao.update(yuceMainEntity);
                }
            } else {
                //下一位审核人才进入，修改审核表状态和主表审核人信息
                if (audit.getAuditFlag().toString().equals("-1")) {
                    audit.setAuditFlag(0);
                    auditDao.update(audit);
                    yuceMainEntity.setAuditorName(audit.getAuditorName());
                    yuceMainEntity.setAuditorId(audit.getAuditorId());
                    yuceMainDao.update(yuceMainEntity);
                    break;
                }
            }

        }
        return true;
    }

    @Override
    public List<JSONObject> getCompanyRegionTree(String jsonData) {
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParam.getString("userId");
        String date = jsonParam.getString("date");
        try {
            date = getFriday(date);
        } catch (Exception e) {
        }
        List<JSONObject> listUsers = userDao.getViewJSONListByCondition(" and id = ?", new Object[]{userId});
        List<String> listCompanyIds = new ArrayList<>();
        List<JSONObject> listResult = new ArrayList<>();
        List<JSONObject> listCompanies = new ArrayList<>();
        for (int i = 0; i < listUsers.size(); i++) {
            String companyId = listUsers.get(i).getString("companyId");
            listCompanyIds.add(companyId);
            companyDao.getChildrenIds(companyId, listCompanyIds);
        }

        String companyIds = "";
        for (int i = 0; i < listCompanyIds.size(); i++) {
            if (yuceMainDao.getYuceStatus(listCompanyIds.get(i))) {
                companyIds += "'" + listCompanyIds.get(i) + "',";
            }
        }
        if (!companyIds.equalsIgnoreCase("201712161613432EAF27DBCCB7D0E6CA")) {
            companyIds += "'201712161613432EAF27DBCCB7D0E6CA',";
        }
        companyIds = companyIds.substring(0, companyIds.length() - 1);
        listCompanies = companyDao.getJSONListByCondition(" AND DEL_FLAG = '0' AND ID IN(" + companyIds + ") AND ID !='2017121617484A2796D8F52B6B558B94' AND ID!='2017121910424ED9AA4F786D5549D72F'  ORDER BY SORT_NO ", new Object[]{});
        //添加公司节点
        for (int i = 0; i < listCompanies.size(); i++) {
            JSONObject objNode = listCompanies.get(i);
            String companyId = objNode.getString("id");
            objNode.put("id", companyId);
            String parentId = objNode.getString("parentId");
            if ("0".equals(listCompanies.get(0).getString("parentId"))) {
                if (com.alibaba.dubbo.common.utils.StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                    objNode.put("pId", "0");
                    objNode.put("open", true);
                } else {
                    objNode.put("pId", parentId);
                    objNode.put("open", false);
                }
            } else {
                objNode.put("pId", "0");
                objNode.put("open", true);
            }
            objNode.put("type", "company");
            objNode.put("companyId", companyId);
            listResult.add(objNode);
        }

        List<JSONObject> regionList = yuceMainDao.getRegionTree(userId, companyIds);
        //添加区域
        for (int i = 0; i < regionList.size(); i++) {
            JSONObject objNode = regionList.get(i);
            String regionId = objNode.getString("regionId");
            objNode.put("name", objNode.getString("regionName") + getStatus(yuceMainDao.getYuceStatus(regionId, date)));
            objNode.put("id", regionId);
            objNode.put("pId", objNode.getString("companyId"));
            objNode.put("type", "region");
            objNode.put("open", false);
            objNode.put("companyId", objNode.getString("companyId"));
            listResult.add(objNode);
        }
        return listResult;
    }

    private String getStatus(Integer status) {
        String flag = "";
        switch (status) {
            case 0:
                flag = "(待审核)";
                break;
            case 1:
                flag = "(已通过)";
                break;
            case 2:
                flag = "(已驳回)";
                break;
            default:
                flag = "(未提交)";
        }
        return flag;
    }

    @Override
    public JSONObject getTitle(String companyId, String regionId) {
        String condition = "";
        if (StringUtils.isBlank(regionId)) {
            condition = " AND t_sys_company.id='" + companyId + "'";
        } else {
            condition = " AND t_sys_region.id = '" + regionId + "'";
        }
        return yuceMainDao.getTitle(condition);
    }
    /**
     * 将传来日期，得到对应的周三
     *
     * @param date
     * @return
     * @throws Exception
     */
    private String getThursday(String date) throws Exception {
        int nowDay = DateUtils.dayForWeek(date);
        if (3 == nowDay) {
            return date;
        } else {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.setTime(format.parse(date));
            c.add(Calendar.DATE, 3 - nowDay);
            return format.format(c.getTime());
        }
    }
    @Override
    public List<JSONObject> getFridayList(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonPalams.getString("userId");
        String companyId = jsonPalams.getString("companyId");
        String firstMonth = jsonPalams.getString("firstMonth");//当前月，格式：2018-09
        String secondMonth = jsonPalams.getString("secondMonth");//同上
        String thirdMonth = jsonPalams.getString("thirdMonth");//同上
        String date = jsonPalams.getString("date");//当前日期  格式：2018-02-12

        StringBuffer condition = new StringBuffer();
        firstMonth=firstMonth.substring(0,4)+"年"+firstMonth.substring(5,firstMonth.length())+"月";
        secondMonth=secondMonth.substring(0,4)+"年"+secondMonth.substring(5,secondMonth.length())+"月";
        thirdMonth=thirdMonth.substring(0,4)+"年"+thirdMonth.substring(5,thirdMonth.length())+"月";
        String wednesday="";
        Date wednesday2 = null;
        try {
            wednesday=getThursday(date);//将传来日期，得到对应的周三
        } catch (Exception e) {
            e.printStackTrace();
        }
        SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        try {
            wednesday2=sDateFormat.parse(wednesday);//将String类型转换问Date类型
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String oldWeek=DateUtils.getBeforeWeek(wednesday2);//根据当前日期获取当前日期的前一周
        oldWeek=oldWeek.substring(0,10);//截取年月日
        if (!com.alibaba.dubbo.common.utils.StringUtils.isEmpty(companyId)) {
            condition.append("AND COMPANY_ID='"+companyId+"'\n");
        }
        //创建人，审核人，抄送人属于用户则可查看到
        if (!com.alibaba.dubbo.common.utils.StringUtils.isEmpty(userId)) {
            condition.append("AND (\n" +
                    "\tREGIONAL_MANAGER_ID = '"+userId+"' \n" +
                    "\tOR (\n" +
                    "\t\tID IN (\n" +
                    "\t\t\tSELECT\n" +
                    "\t\t\t\tMAIN_ID\n" +
                    "\t\t\tFROM\n" +
                    "\t\t\t\tt_sys_audit\n" +
                    "\t\t\tWHERE\n" +
                    "\t\t\t\tAUDITOR_ID = '"+userId+"'\n" +
                    "\t\t)\n" +
                    "\t\tAND AUDIT_FLAG <> '-1'\n" +
                    "\t)\n" +
                    "\tOR (\n" +
                    "\t\tID IN (\n" +
                    "\t\t\tSELECT\n" +
                    "\t\t\t\tMAIN_ID\n" +
                    "\t\t\tFROM\n" +
                    "\t\t\t\tt_sys_copier\n" +
                    "\t\t\tWHERE\n" +
                    "\t\t\t\tCOPIER_ID = '"+userId+"'\n" +
                    "\t\t)\n" +
                    "\t\tAND AUDIT_FLAG <> '-1'\n" +
                    "\t)\n" +
                    ")\n");
        }
        condition.append("AND AUDIT_FLAG=1");
        List<JSONObject> list = yuceMainDao.getFridayList(condition.toString(),firstMonth,secondMonth,thirdMonth,oldWeek,wednesday);
        return list;
    }
}
